package com.zking.myservlet.user;

import com.zking.dao.UserDao;
import com.zking.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/manage/userSelectByPage")
public class UserSelectByPage extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理请求的编码，解决中文乱码
        request.setCharacterEncoding("utf-8");
        // 处理响应的编码，解决中文乱码
        response.setContentType("text/html;charset=utf-8");

        // 输出调试信息
        System.out.println("UserSelectByPage===进来");

        // 默认的页码和页面大小
        int pageIndex = 1;
        int pageSize = 2;

        // 获取请求中的 pageIndex 参数，如果存在则转换为整数
        String temp = request.getParameter("pageIndex");
        if (temp != null) {
            pageIndex = Integer.parseInt(temp);
        }

        // 调用 UserDao 类的方法查询用户列表和最大页数
        List<User> list = UserDao.getUsersByPage(pageIndex, pageSize);
        int maxPage = UserDao.getMaxPage(pageSize);

        // 将查询结果和分页信息设置到请求属性中，以便传递给 JSP 页面
        request.setAttribute("list", list);//把后台数据传递给jsp页面
        request.setAttribute("pageIndex", pageIndex);
        request.setAttribute("maxPage", maxPage);

        // 转发请求到 user.jsp 页面进行展示
        request.getRequestDispatcher("user.jsp").forward(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET 请求直接调用 doPost 处理
        doPost(request, response);
    }
}
